package com.scm.biz.action;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.scm.biz.bean.SysRole;
import com.scm.biz.bean.SysRoleResource;
import com.scm.biz.enums.LogOperation;
import com.scm.biz.query.SysRoleQuery;
import com.scm.biz.service.ResourceService;
import com.scm.biz.service.SysRoleResourceService;
import com.scm.biz.service.SysRoleService;
import com.scm.core.bean.resp.RespBean;
import com.scm.core.interceptor.LogConfig;

@Controller
@RequestMapping("/sysrole")
public class SysRoleAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7935830951665903576L;
	@Resource
	private SysRoleService sysRoleService;
	@Resource
	private ResourceService resourceService;
	@Resource
	SysRoleResourceService sysRoleResourceService;
	@RequestMapping("/list")
	//@LogConfig(operationModule=LogOperation.USER,description="用户查询")
	public ModelAndView list(String name,Integer pageNo) throws Exception {
		SysRoleQuery sysRoleQuery = new SysRoleQuery();
		sysRoleQuery.setPageNo(pageNo);
		sysRoleQuery.setName(name);
		ModelAndView mv = new ModelAndView("system/sys_role_list");
		
		mv.addObject("name", name);
		mv.addObject("pageNo", pageNo);
		mv.addObject("sysRoleList", sysRoleService.selectList(sysRoleQuery));
		mv.addObject("splitPage", sysRoleQuery.getSplitPage());
		return mv;
	}
	@RequestMapping("/del")
	public String del(String userId) throws Exception {
		int id = Integer.valueOf(userId);
		sysRoleService.deleteById(id);
		return "redirect:/sysrole/list";
	}
	@RequestMapping("/edit")
	public ModelAndView edit(Integer id) throws Exception {
		SysRole sysRole = sysRoleService.selectById(id);
		ModelAndView mv = new ModelAndView("system/sys_role_edit");
		mv.addObject("sysRole",sysRole);
		mv.addObject("resourceList",resourceService.selectList());
		mv.addObject("roleResourceList",resourceService.selectListByRoleId(id));
		return mv;
	}
	@RequestMapping("/save")
	@ResponseBody
	@LogConfig(operationModule=LogOperation.USER,description="角色修改")
	public RespBean<String> save(Integer id,String name,String memo,Integer[] resources) throws Exception {
		RespBean<String> respBean = new RespBean<>();
		SysRole sysRole = sysRoleService.selectById(id);
		sysRole.setName(name);
		sysRole.setMemo(memo);
		sysRoleResourceService.deleteByRoleId(id);
		if(resources !=null){
			SysRoleResource sysRoleResource = null;
			for(Integer resouceId:resources){
				sysRoleResource = new SysRoleResource();
				sysRoleResource.setResourceId(resouceId);
				sysRoleResource.setRoleId(id);
				sysRoleResourceService.insert(sysRoleResource);
			}
		}
		respBean.setBody("success");
		return respBean;
	}
}
